<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <template #header>
        <div class="card-header">
          <h2>个人信息</h2>
        </div>
      </template>
      
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="4" animated />
      </div>
      
      <div v-else class="profile-content">
        <div class="avatar-section">
          <el-avatar 
            :size="100" 
            :src="avatarUrl" 
            class="user-avatar" 
          />
          <el-upload
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleAvatarChange"
          >
            <el-button type="primary" size="small">更换头像</el-button>
          </el-upload>
        </div>
        
        <el-form 
          ref="profileFormRef"
          :model="profileForm"
          :rules="formRules"
          label-width="100px"
          class="profile-form"
        >
            <el-form-item label="姓名" prop="name">
            <el-input v-model="profileForm.name" disabled />
          </el-form-item>
          <el-form-item label="账号" prop="account">
            <el-input v-model="profileForm.account" disabled />
          </el-form-item>
          
          <el-form-item label="用户角色" prop="role">
            <el-input v-model="profileForm.role" disabled />
          </el-form-item>
          
          <el-form-item v-if="profileForm.role === '学生'" label="班级" prop="className">
            <el-input v-model="profileForm.className" disabled />
          </el-form-item>
          
          <el-divider content-position="left">安全设置</el-divider>
          
          <el-form-item label="当前密码" prop="currentPassword">
            <el-input 
              v-model="profileForm.currentPassword" 
              type="password"
              placeholder="请输入当前密码"
              show-password
            />
          </el-form-item>
          
          <el-form-item label="新密码" prop="newPassword">
            <el-input 
              v-model="profileForm.newPassword" 
              type="password"
              placeholder="请输入新密码"
              show-password
            />
          </el-form-item>
          
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input 
              v-model="profileForm.confirmPassword" 
              type="password"
              placeholder="请再次输入新密码"
              show-password
            />
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="submitForm">保存修改</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '@/stores/modules/user-student'
import { changePassword } from '@/api/th/auth'
import { useExamStore } from '@/stores/modules/exam-student'
import md5 from 'js-md5'; 

const router = useRouter()
const userStore = useUserStore()
const examStore = useExamStore()
const loading = ref(true)
const avatarUrl = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png')
const profileFormRef = ref(null)

// 表单数据
const profileForm = reactive({
  account: '',
  role: '',
  className: '',
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const formRules = reactive({
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6,message: '密码长度至少6个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 30, message: '长度需在6-30位之间', trigger: ['blur', 'input'] },
    { 
      pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/,
      message: '需包含字母和数字',
      trigger: ['blur', 'input']
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== profileForm.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
})

// 加载用户信息
const loadUserInfo = () => {
  loading.value = true
  
  // 从用户仓库获取信息
  const userInfo = userStore.userInfo
  
  if (userInfo) {
    profileForm.account = userInfo.account || ''
    profileForm.role = userInfo.role || ''
    profileForm.className = userInfo.classInfo?.name || ''
    profileForm.name = userInfo.name || ''
    loading.value = false
  } else {
    // 如果用户信息不存在，尝试重新获取
    userStore.fetchUserInfo().then(() => {
      const refreshedInfo = userStore.userInfo
      if (refreshedInfo) {
        profileForm.account = refreshedInfo.account || ''
        profileForm.role = refreshedInfo.role || ''
        profileForm.className = refreshedInfo.classInfo?.name || ''
      }
      loading.value = false
    }).catch(() => {
      loading.value = false
      ElMessage.error('获取用户信息失败')
    })
  }
}

// 处理头像选择
const handleAvatarChange = (file) => {
  // 这里只是简单模拟，实际应该上传到服务器
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    avatarUrl.value = reader.result
    ElMessage.success('头像更新成功')
  }
}

// 提交表单
const submitForm = async () => {
  if (!profileForm.currentPassword && !profileForm.newPassword && !profileForm.confirmPassword) {
    ElMessage.info('没有需要保存的更改')
    return
  }
  
  await profileFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 调用API更新密码
        const current = md5(profileForm.currentPassword);
        const newpwd = md5(profileForm.newPassword)
        await changePassword({
          currentPassword: current,
          newPassword: newpwd
        })
        // 重置密码字段
        profileForm.currentPassword = ''
        profileForm.newPassword = ''
        profileForm.confirmPassword = ''
        ElMessage.success('密码修改成功')
        userStore.logout()
        examStore.clearAllExamData()
        router.push('/login')
        
      } catch (error) {
        console.error('请求错误:', error)
        ElMessage.error('密码修改失败，请稍后重试')
      }
    }
  })
}

// 重置表单
const resetForm = () => {
  profileForm.currentPassword = ''
  profileForm.newPassword = ''
  profileForm.confirmPassword = ''
  profileFormRef.value.resetFields()
}

// 页面加载时获取用户信息
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
.profile-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

.loading-container {
  padding: 20px;
}

.profile-content {
  padding: 10px 0;
}

.avatar-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.user-avatar {
  margin-bottom: 15px;
  border: 4px solid #eef5fe;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.avatar-uploader {
  margin-top: 10px;
}

.profile-form {
  max-width: 600px;
  margin: 0 auto;
}
</style> 